package com.dzl.enterprise.service.impl;

import com.dzl.base.service.BaseServiceImpl;
import com.dzl.config.exception.CommonException;
import com.dzl.constant.CommonConstants;
import com.dzl.enterprise.dao.WelfareEnterpriseOrganizationMapper;
import com.dzl.enterprise.pojo.WelfareEnterpriseOrganization;
import com.dzl.enterprise.pojo.dto.*;
import com.dzl.enterprise.pojo.vo.WelfareEnterpriseOrganizationTreeVo;
import com.dzl.enterprise.service.WelfareEnterpriseOrganizationService;
import com.dzl.userwx.pojo.WelfareUserOrganization;
import com.dzl.userwx.pojo.WelfareUserWx;
import com.dzl.userwx.service.WelfareUserOrganizationService;
import com.dzl.userwx.service.WelfareUserWxService;
import com.dzl.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 企业组织信息表(WelfareEnterpriseOrganization)表服务实现类
 * @author ChenLong
 * @date 2021-09-07 15:28:25
 */
@Slf4j
@Service
public class WelfareEnterpriseOrganizationServiceImpl extends BaseServiceImpl<WelfareEnterpriseOrganization> implements WelfareEnterpriseOrganizationService {

    @Autowired
    private WelfareEnterpriseOrganizationMapper mapper;
    @Autowired
    private WelfareUserWxService welfareUserWxService;
    @Autowired
    private WelfareUserOrganizationService welfareUserOrganizationService;

    // 导入最大条数
    private static final int IMPORT_MAX_LIMIT = 1000;

    @Override
    public List<WelfareEnterpriseOrganizationTreeVo> getEnterpriseOrganizationTree(Integer enterpriseId) {
        WelfareEnterpriseOrganization welfareEnterpriseOrganizationSelect = new WelfareEnterpriseOrganization();
        welfareEnterpriseOrganizationSelect.setEnterpriseId(enterpriseId);
        welfareEnterpriseOrganizationSelect.setStatus(1);
        List<WelfareEnterpriseOrganizationTreeVo> enterpriseOrganizationList = mapper.getEnterpriseOrganizationTreeVo(welfareEnterpriseOrganizationSelect);
        return findTree(enterpriseOrganizationList);
    }

    /**
     * 获取节点树
     *
     * @param allWelfareGoodsClassify 商品分类列表
     * @return java.util.List<com.dzl.goods.entity.WelfareGoodsClassify>
     * @author ChenLong
     * @since 2021-05-18 16:34:07
     **/
    public List<WelfareEnterpriseOrganizationTreeVo> findTree(List<WelfareEnterpriseOrganizationTreeVo> allWelfareGoodsClassify) {
        try {
            // 根节点
            List<WelfareEnterpriseOrganizationTreeVo> rootWelfareGoodsClassify = new ArrayList<>();
            for (WelfareEnterpriseOrganizationTreeVo nav : allWelfareGoodsClassify) {
                //父节点是0的，为根节点
                if (nav.getParentId() == 0) {
                    nav.setIdPath(nav.getId().toString());
                    rootWelfareGoodsClassify.add(nav);
                }
            }
            // 根据WelfareGoodsClassify类的order排序
            Collections.sort(rootWelfareGoodsClassify, sort());
            //为根节点设置子节点，getClild是递归调用的
            for (WelfareEnterpriseOrganizationTreeVo nav : rootWelfareGoodsClassify) {
                // 获取根节点下的所有子节点 使用getChild方法
                List<WelfareEnterpriseOrganizationTreeVo> childList = getChild(nav.getId(),nav.getIdPath(), allWelfareGoodsClassify);
                nav.setChildren(childList);//给根节点设置子节点
            }
            return rootWelfareGoodsClassify;
        } catch (Exception e) {
            log.error("findTree e: " + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 获取子节点
     *
     * @param id                      行id
     * @param allWelfareGoodsClassify 商品分类列表
     * @return java.util.List<com.dzl.goods.entity.WelfareGoodsClassify>
     * @author ChenLong
     * @since 2021-05-18 16:33:03
     **/
    public List<WelfareEnterpriseOrganizationTreeVo> getChild(Integer id,String parentIds, List<WelfareEnterpriseOrganizationTreeVo> allWelfareGoodsClassify) {
        //子菜单
        List<WelfareEnterpriseOrganizationTreeVo> childList = new ArrayList<>();
        for (WelfareEnterpriseOrganizationTreeVo nav : allWelfareGoodsClassify) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            // 相等说明：为该根节点的子节点。
            if (nav.getParentId().equals(id)) {
                nav.setIdPath(parentIds+"/"+nav.getId());
                childList.add(nav);
            }
        }
        // 递归
        for (WelfareEnterpriseOrganizationTreeVo nav : childList) {
            nav.setChildren(getChild(nav.getId(),nav.getIdPath(), allWelfareGoodsClassify));
        }
        Collections.sort(childList, sort()); //排序
        // 如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

    /**
     * 排序,根据sort排序
     *
     * @param
     * @return java.util.Comparator<com.dzl.goods.entity.WelfareGoodsClassify>
     * @author ChenLong
     * @since 2021-05-18 16:33:48
     **/
    public Comparator<WelfareEnterpriseOrganizationTreeVo> sort() {
        Comparator<WelfareEnterpriseOrganizationTreeVo> comparator = new Comparator<WelfareEnterpriseOrganizationTreeVo>() {
            @Override
            public int compare(WelfareEnterpriseOrganizationTreeVo o1, WelfareEnterpriseOrganizationTreeVo o2) {
                if (!o1.getLevel().equals(o2.getLevel())) {
                    return o1.getLevel() - o2.getLevel();
                }
                return 0;
            }
        };
        return comparator;
    }

    public static final int MAX_LENGTH = 10;

    @Override
    public JsonResult<Integer> addImportOrganization(List<List<String>> list, Integer orgId) {
        if (EmptyUtils.isEmpty(list) || list.size() < 1) {
            return new JsonResult<>(null, 1001, "请填写组织信息");
        }
        if (list.size() > IMPORT_MAX_LIMIT) {
            return new JsonResult<>(null, 1002, "超过导入条数限制：" + IMPORT_MAX_LIMIT);
        }
        // 存放组织ID的Map
        Map<String, Integer> orgIdMap = new HashMap<>();
        for (List<String> item : list) {
            String itemOrgNameLev1 = "";
            String itemOrgNameLev2 = "";
            String itemOrgNameLev3 = "";
            String itemOrgNameLev4 = "";
            String itemOrgNameLev5 = "";

            if (item.size() > 0) {
                itemOrgNameLev1 = item.get(0);
                if (EmptyUtils.isNotEmpty(itemOrgNameLev1) && itemOrgNameLev1.length() > MAX_LENGTH) {
                    throw new CommonException("名称长度应在十个字符内");
                }
            }
            if (item.size() > 1) {
                itemOrgNameLev2 = item.get(1);
                if (EmptyUtils.isNotEmpty(itemOrgNameLev2) && itemOrgNameLev2.length() > MAX_LENGTH) {
                    throw new CommonException("名称长度应在十个字符内");
                }
            }
            if (item.size() > 2) {
                itemOrgNameLev3 = item.get(2);
                if (EmptyUtils.isNotEmpty(itemOrgNameLev3) && itemOrgNameLev3.length() > MAX_LENGTH) {
                    throw new CommonException("名称长度应在十个字符内");
                }
            }
            if (item.size() > 3) {
                itemOrgNameLev4 = item.get(3);
                if (EmptyUtils.isNotEmpty(itemOrgNameLev4) && itemOrgNameLev4.length() > MAX_LENGTH) {
                    throw new CommonException("名称长度应在十个字符内");
                }
            }
            if (item.size() > 4) {
                itemOrgNameLev5 = item.get(4);
                if (EmptyUtils.isNotEmpty(itemOrgNameLev5) && itemOrgNameLev5.length() > MAX_LENGTH) {
                    throw new CommonException("名称长度应在十个字符内");
                }
            }

            // 组织ID
            int lev1Id;
            int lev2Id;
            int lev3Id;
            int lev4Id;
            int lev5Id;
            // 第1列
            if (EmptyUtils.isNotEmpty(itemOrgNameLev1)) {
                String key = itemOrgNameLev1;
                if (!orgIdMap.containsKey(key)) {
                    WelfareEnterpriseOrganization welfareEnterpriseOrganizationAdd = new WelfareEnterpriseOrganization();
                    buildEnterpriseOrganization(welfareEnterpriseOrganizationAdd, orgId, 0, itemOrgNameLev1, 1);// 第1级父Id为0
                    mapper.insertUseGeneratedKeys(welfareEnterpriseOrganizationAdd);
                    lev1Id = welfareEnterpriseOrganizationAdd.getId();
                    orgIdMap.put(key, lev1Id);
                } else {
                    lev1Id = orgIdMap.get(key);
                }
            } else {
                continue;
            }
            // 第2列
            if (EmptyUtils.isNotEmpty(itemOrgNameLev2)) {
                String key = itemOrgNameLev1 + "_" + itemOrgNameLev2;
                if (!orgIdMap.containsKey(key)) {
                    WelfareEnterpriseOrganization welfareEnterpriseOrganizationAdd = new WelfareEnterpriseOrganization();
                    buildEnterpriseOrganization(welfareEnterpriseOrganizationAdd, orgId, lev1Id, itemOrgNameLev2, 2);// 第2级父Id为第1级的ID
                    mapper.insertUseGeneratedKeys(welfareEnterpriseOrganizationAdd);
                    lev2Id = welfareEnterpriseOrganizationAdd.getId();
                    orgIdMap.put(key, lev2Id);
                } else {
                    lev2Id = orgIdMap.get(key);
                }
            } else {
                continue;
            }
            // 第3列
            if (EmptyUtils.isNotEmpty(itemOrgNameLev3)) {
                String key = itemOrgNameLev1 + "_" + itemOrgNameLev2 + "_" + itemOrgNameLev3;
                if (!orgIdMap.containsKey(key)) {
                    WelfareEnterpriseOrganization welfareEnterpriseOrganizationAdd = new WelfareEnterpriseOrganization();
                    buildEnterpriseOrganization(welfareEnterpriseOrganizationAdd, orgId, lev2Id, itemOrgNameLev3, 3);// 第3级父Id为第2级的ID
                    mapper.insertUseGeneratedKeys(welfareEnterpriseOrganizationAdd);
                    lev3Id = welfareEnterpriseOrganizationAdd.getId();
                    orgIdMap.put(key, lev3Id);
                } else {
                    lev3Id = orgIdMap.get(key);
                }
            } else {
                continue;
            }
            // 第4列
            if (EmptyUtils.isNotEmpty(itemOrgNameLev4)) {
                String key = itemOrgNameLev1 + "_" + itemOrgNameLev2 + "_" + itemOrgNameLev3 + "_" + itemOrgNameLev4;
                if (!orgIdMap.containsKey(key)) {
                    WelfareEnterpriseOrganization welfareEnterpriseOrganizationAdd = new WelfareEnterpriseOrganization();
                    buildEnterpriseOrganization(welfareEnterpriseOrganizationAdd, orgId, lev3Id, itemOrgNameLev4, 4);// 第4级父Id为第3级的ID
                    mapper.insert(welfareEnterpriseOrganizationAdd);
                    lev4Id = welfareEnterpriseOrganizationAdd.getId();
                    orgIdMap.put(key, lev4Id);
                } else {
                    lev4Id = orgIdMap.get(key);
                }
            } else {
                continue;
            }
            // 第5列
            if (EmptyUtils.isNotEmpty(itemOrgNameLev5)) {
                String key = itemOrgNameLev1 + "_" + itemOrgNameLev2 + "_" + itemOrgNameLev3 + "_" + itemOrgNameLev4 + "_" + itemOrgNameLev5;
                if (!orgIdMap.containsKey(key)) {
                    WelfareEnterpriseOrganization welfareEnterpriseOrganizationAdd = new WelfareEnterpriseOrganization();
                    buildEnterpriseOrganization(welfareEnterpriseOrganizationAdd, orgId, lev4Id, itemOrgNameLev5, 5);// 第4级父Id为第3级的ID
                    mapper.insert(welfareEnterpriseOrganizationAdd);
                    lev5Id = welfareEnterpriseOrganizationAdd.getId();
                    orgIdMap.put(key, lev5Id);
                }
            }
        }
        int result = 0;
        return new JsonResult<>(result, HttpCode.SUCCESS);
    }

    /**
     * @param welfareEnterpriseOrganizationAdd EnterpriseOrganization对象
     * @param orgId                            组织Id
     * @param name                             名称
     * @return void
     * @author ChenLong
     * @date 2021-09-08 09:15:43
     **/
    private void buildEnterpriseOrganization(WelfareEnterpriseOrganization welfareEnterpriseOrganizationAdd, Integer orgId, Integer parentId, String name, Integer level) {
        welfareEnterpriseOrganizationAdd.setEnterpriseId(orgId);
        welfareEnterpriseOrganizationAdd.setParentId(parentId);
        welfareEnterpriseOrganizationAdd.setLevel(level);
        welfareEnterpriseOrganizationAdd.setName(name);
        welfareEnterpriseOrganizationAdd.setCreateTime(new Date());
        welfareEnterpriseOrganizationAdd.setStatus(1);
    }

    @Override
    public JsonResult<Integer> addImportUserForOrganization(List<List<String>> list, Integer enterpriseId, UserOrganizationDto userOrganizationDto) {
        if (EmptyUtils.isEmpty(list)) {
            return new JsonResult<>(null, 1001, "请填写成员信息");
        }
        if (list.size() > IMPORT_MAX_LIMIT) {
            return new JsonResult<>(null, 1002, "超过导入条数限制：" + IMPORT_MAX_LIMIT);
        }
        int result = 0;//新增条数
        //查出该企业下所有用户账号
        WelfareUserWx query = new WelfareUserWx();
        query.setStatus(CommonConstants.YES);
        query.setEnterpriseId(enterpriseId);
        List<WelfareUserWx> welfareUserWxes = welfareUserWxService.select(query);
        //通过过滤器记录已存在的账号/手机号
        //BloomFilter myBloomFilterExists = new BloomFilter();
        //BloomFilter myBloomFilterCreats = new BloomFilter();
        Set setExists = new HashSet();
        Set setCreats = new HashSet();
        Set setPhones = new HashSet();
        if (EmptyUtils.isNotEmpty(welfareUserWxes)) {
            for (int i = 0; i < welfareUserWxes.size(); i++) {
                setExists.add(welfareUserWxes.get(i).getPhone());
                // setExists.add(welfareUserWxes.get(i).getPhone());
            }
        }
        // 插入记录到用户表
        //List<WelfareUserWx> welfareUserWxList = new ArrayList<>();

        //异步批量添加，将list分隔成多个任务单独开启线程去执行，每个线程导100个
        int count1 = list.size() / 100;
        int count2 = list.size() % 100;
        if (count1 == 0) {
            count1 = 1;
        } else {
            if (count2 > 0) {
                count1++;
            }
        }
        for (int i = 0; i < count1; i++) {
            List<List<String>> list_ = new ArrayList<>();
            for (int j = 0; j < list.size(); j++) {
                if (j + i * 100 < list.size()) {
                    List<String> item = list.get(j + i * 100);
                    if (item.size() < 2) {
                        throw new CommonException("请填写完整信息");
                    }
                    if (EmptyUtils.isEmpty(item.get(0))) {
                        throw new CommonException("请填写用户名");
                    }
                    if (EmptyUtils.isEmpty(item.get(1))) {
                        throw new CommonException("请填写手机号");
                    }
                    if (EmptyUtils.isNotEmpty(item.get(0)) && item.get(0).length() > MAX_LENGTH) {
                        throw new CommonException("名称长度应在十个字符内");
                    }
                    String userName = item.get(0);
                    String phoneNumber = item.get(1);
                    //手机号规则校验
                    String PhonePattern = "^1[3456789]\\d{9}$";
                    if (!Pattern.compile(PhonePattern).matcher(phoneNumber).matches()) {
                        throw new CommonException("账号格式不正确：" + phoneNumber);
                    }
                    if (setPhones.contains(phoneNumber)) {
                        throw new CommonException("帐号重复：" + phoneNumber);
                    }
                    if (j > 0 && j % 100 == 0) {
                        break;
                    }
                    list_.add(item);
                    setPhones.add(phoneNumber);
                }
            }
            if (EmptyUtils.isNotEmpty(list_)) {
              //  syncInitDataServiceImpl.addImportUserForOrganization(list_, enterpriseId, userOrganizationDto, setExists, setCreats);
            }
        }
        return new JsonResult<>(result, HttpCode.SUCCESS);
    }


    @Override
    public Integer addEnterpriseOrganization(EnterpriseOrganizationAddDto enterpriseOrganizationAddDto) {
        WelfareEnterpriseOrganization welfareEnterpriseOrganizationSelect = new WelfareEnterpriseOrganization();
        welfareEnterpriseOrganizationSelect.setParentId(enterpriseOrganizationAddDto.getParentId());
        welfareEnterpriseOrganizationSelect.setEnterpriseId(enterpriseOrganizationAddDto.getEnterpriseId());
        welfareEnterpriseOrganizationSelect.setName(enterpriseOrganizationAddDto.getName());
        if (mapper.selectCount(welfareEnterpriseOrganizationSelect) > 0) {
            throw new CommonException("该组织已经存在");
        }
        WelfareEnterpriseOrganization welfareEnterpriseOrganizationAdd = new WelfareEnterpriseOrganization();
        welfareEnterpriseOrganizationAdd.setEnterpriseId(enterpriseOrganizationAddDto.getEnterpriseId());
        welfareEnterpriseOrganizationAdd.setParentId(enterpriseOrganizationAddDto.getParentId());
        welfareEnterpriseOrganizationAdd.setLevel(enterpriseOrganizationAddDto.getLevel());
        welfareEnterpriseOrganizationAdd.setName(enterpriseOrganizationAddDto.getName());
        welfareEnterpriseOrganizationAdd.setCreateTime(new Date());
        welfareEnterpriseOrganizationAdd.setStatus(1);
        return mapper.insert(welfareEnterpriseOrganizationAdd);
    }

    @Override
    public Integer updateEnterpriseOrganization(EnterpriseOrganizationUpdDto enterpriseOrganizationUpdDto) {
        WelfareEnterpriseOrganization welfareEnterpriseOrganizationUpd = new WelfareEnterpriseOrganization();
        welfareEnterpriseOrganizationUpd.setId(enterpriseOrganizationUpdDto.getId());
        welfareEnterpriseOrganizationUpd.setName(enterpriseOrganizationUpdDto.getName());
        welfareEnterpriseOrganizationUpd.setUpdateTime(new Date());
        return mapper.updateByPrimaryKeySelective(welfareEnterpriseOrganizationUpd);
    }

    @Override
    public Integer deleteEnterpriseOrganization(EnterpriseOrganizationDelDto enterpriseOrganizationDelDto) {
        Integer level = enterpriseOrganizationDelDto.getLevel();
        //查询某级组织下的用户
        String organizationIdName = "firstOrganizationId";
        //查询该企业下根目录下的所有用户
        Example example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                .andIsNull("firstOrganizationId")
                .andEqualTo("enterpriseId", enterpriseOrganizationDelDto.getEnterpriseId()))
                .build();
        WelfareEnterpriseOrganization welfareEnterpriseOrganization = mapper.selectByPrimaryKey(enterpriseOrganizationDelDto.getId());
        if(welfareEnterpriseOrganization.getLevel() != level){
            throw new CommonException("传参有误，请检查level级别");
        }
        if(level == 2){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("secondOrganizationId")
                    .andEqualTo("firstOrganizationId", welfareEnterpriseOrganization.getParentId()))
                    .build();
            organizationIdName = "secondOrganizationId";
        }else if(level == 3){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("thirdOrganizationId")
                    .andEqualTo("secondOrganizationId", welfareEnterpriseOrganization.getParentId()))
                    .build();
            organizationIdName = "thirdOrganizationId";
        }else if(level == 4){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("fourthOrganizationId")
                    .andEqualTo("thirdOrganizationId", welfareEnterpriseOrganization.getParentId()))
                    .build();
            organizationIdName = "fourthOrganizationId";
        }else if(level == 5){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("fifthOrganizationId")
                    .andEqualTo("fourthOrganizationId", welfareEnterpriseOrganization.getParentId()))
                    .build();
            organizationIdName = "fifthOrganizationId";
        }
        List<WelfareUserOrganization> list = welfareUserOrganizationService.selectByExample(example);
        Set<Integer> userIdSet = new HashSet<>();
        if(EmptyUtils.isNotEmpty(list)){
            List<Integer> userIdList = list.stream().map(WelfareUserOrganization::getUserId).collect(Collectors.toList());
            userIdSet = new HashSet<>(userIdList);
        }
        //查询一级组织以及其下的二级三级四级五级组织下的用户
        Example example_ = Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                .andEqualTo(organizationIdName, enterpriseOrganizationDelDto.getId()))
                .build();
        List<WelfareUserOrganization> list_ = welfareUserOrganizationService.selectByExample(example_);
        //删除原用户组织
        WelfareUserOrganization deleteParam = new WelfareUserOrganization();
        if(level == 1){
            deleteParam.setFirstOrganizationId(enterpriseOrganizationDelDto.getId());
        }else if(level == 2){
            deleteParam.setSecondOrganizationId(enterpriseOrganizationDelDto.getId());
        }else if(level == 3){
            deleteParam.setThirdOrganizationId(enterpriseOrganizationDelDto.getId());
        }else if(level == 4){
            deleteParam.setFourthOrganizationId(enterpriseOrganizationDelDto.getId());
        }else if(level == 5){
            deleteParam.setFifthOrganizationId(enterpriseOrganizationDelDto.getId());
        }
        welfareUserOrganizationService.delete(deleteParam);
        //删除组织
        mapper.deleteByPrimaryKey(enterpriseOrganizationDelDto.getId());
        //批量新增用户组织
        List<WelfareUserOrganization> addlist = new ArrayList<>();
        if(EmptyUtils.isNotEmpty(list_)){
            List<Integer> userIdList_ = list_.stream().map(WelfareUserOrganization::getUserId).collect(Collectors.toList());
            Set<Integer> userIdSet_ = new HashSet<>(userIdList_);
            Integer firstOrganizationId = null;
            Integer secondOrganizationId = null;
            Integer thirdOrganizationId = null;
            Integer fourthOrganizationId = null;
            if(level == 2){
                firstOrganizationId = welfareEnterpriseOrganization.getParentId();
            }else if(level == 3){
                secondOrganizationId = welfareEnterpriseOrganization.getParentId();
                WelfareEnterpriseOrganization secondWelfareEnterpriseOrganization = mapper.selectByPrimaryKey(secondOrganizationId);
                firstOrganizationId = secondWelfareEnterpriseOrganization.getParentId();
            }else if(level == 4){
                thirdOrganizationId = welfareEnterpriseOrganization.getParentId();
                WelfareEnterpriseOrganization thirdWelfareEnterpriseOrganization = mapper.selectByPrimaryKey(thirdOrganizationId);
                secondOrganizationId = thirdWelfareEnterpriseOrganization.getParentId();
                WelfareEnterpriseOrganization secondWelfareEnterpriseOrganization = mapper.selectByPrimaryKey(secondOrganizationId);
                firstOrganizationId = secondWelfareEnterpriseOrganization.getParentId();
            }else if(level == 5){
                fourthOrganizationId = welfareEnterpriseOrganization.getParentId();
                WelfareEnterpriseOrganization fourthWelfareEnterpriseOrganization = mapper.selectByPrimaryKey(fourthOrganizationId);
                thirdOrganizationId = fourthWelfareEnterpriseOrganization.getParentId();
                WelfareEnterpriseOrganization thirdWelfareEnterpriseOrganization = mapper.selectByPrimaryKey(thirdOrganizationId);
                secondOrganizationId = thirdWelfareEnterpriseOrganization.getParentId();
                WelfareEnterpriseOrganization secondWelfareEnterpriseOrganization = mapper.selectByPrimaryKey(secondOrganizationId);
                firstOrganizationId = secondWelfareEnterpriseOrganization.getParentId();
            }
            for (Integer id:userIdSet_) {
                if(!userIdSet.contains(id)){
                    WelfareUserOrganization welfareUserOrganization = new WelfareUserOrganization();
                    welfareUserOrganization.setEnterpriseId(enterpriseOrganizationDelDto.getEnterpriseId());
                    welfareUserOrganization.setFirstOrganizationId(firstOrganizationId);
                    welfareUserOrganization.setSecondOrganizationId(secondOrganizationId);
                    welfareUserOrganization.setThirdOrganizationId(thirdOrganizationId);
                    welfareUserOrganization.setFourthOrganizationId(fourthOrganizationId);
                    welfareUserOrganization.setUserId(id);
                    welfareUserOrganization.setStatus(CommonConstants.YES);
                    welfareUserOrganization.setCreateTime(new Date());
                    welfareUserOrganization.setUpdateTime(new Date());
                    addlist.add(welfareUserOrganization);
                }
            }
        }
        //批量新增组织
        if(EmptyUtils.isNotEmpty(addlist)){
            return welfareUserOrganizationService.insertList(addlist);
        }
        return 0;
    }

    @Override
    public Integer addUserForEnterpriseOrganization(OrganizationUserAddDto organizationUserAddDto) {
        WelfareUserWx welfareUserWxRes;
        WelfareUserOrganization welfareUserOrganization = new WelfareUserOrganization();
        // 判断在微信用户表是否存在
        Example userPhoneExample = new Example(WelfareUserWx.class);
        userPhoneExample.createCriteria().andEqualTo("enterpriseId", organizationUserAddDto.getEnterpriseId())
                .andEqualTo("phone", organizationUserAddDto.getPhone())
                .andNotEqualTo("status", 0);
        List<WelfareUserWx> userWxList = welfareUserWxService.selectByExample(userPhoneExample);
        welfareUserWxRes = EmptyUtils.isNotEmpty(userWxList)?userWxList.get(0):null;

        if (EmptyUtils.isEmpty(welfareUserWxRes)) {
            WelfareUserWx welfareUserWx = new WelfareUserWx();
            welfareUserWx.setEnterpriseId(organizationUserAddDto.getEnterpriseId());
            welfareUserWx.setPhone(organizationUserAddDto.getPhone());
            welfareUserWx.setPassword(PasswordUtil.AESEncrypt("123456"));
            welfareUserWx.setPayPassword(PasswordUtil.AESEncrypt("1234"));
            welfareUserWx.setCreateTime(new Date());
            welfareUserWx.setUserName(organizationUserAddDto.getName());
            welfareUserWx.setStatus(1);
            welfareUserWxService.insertSelective(welfareUserWx);
            welfareUserOrganization.setUserId(welfareUserWx.getId());
        } else {
            welfareUserOrganization.setUserId(welfareUserWxRes.getId());
        }
        //查询该用户在新组织下是否存在
        Example example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                .andIsNull("firstOrganizationId")
                .andEqualTo("userId", welfareUserOrganization.getUserId())
                .andEqualTo("enterpriseId", organizationUserAddDto.getEnterpriseId()))
                .build();
        if(EmptyUtils.isNotEmpty(organizationUserAddDto.getFifthOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andEqualTo("userId", welfareUserOrganization.getUserId())
                    .andEqualTo("fifthOrganizationId", organizationUserAddDto.getFifthOrganizationId()))
                    .build();
        }else if(EmptyUtils.isNotEmpty(organizationUserAddDto.getFourthOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("fifthOrganizationId")
                    .andEqualTo("userId", welfareUserOrganization.getUserId())
                    .andEqualTo("fourthOrganizationId", organizationUserAddDto.getFourthOrganizationId()))
                    .build();
        }else if(EmptyUtils.isNotEmpty(organizationUserAddDto.getThirdOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("fourthOrganizationId")
                    .andEqualTo("userId", welfareUserOrganization.getUserId())
                    .andEqualTo("thirdOrganizationId", organizationUserAddDto.getThirdOrganizationId()))
                    .build();
        }else if(EmptyUtils.isNotEmpty(organizationUserAddDto.getSecondOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("thirdOrganizationId")
                    .andEqualTo("userId", welfareUserOrganization.getUserId())
                    .andEqualTo("secondOrganizationId", organizationUserAddDto.getSecondOrganizationId()))
                    .build();
        }else if(EmptyUtils.isNotEmpty(organizationUserAddDto.getFirstOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("secondOrganizationId")
                    .andEqualTo("userId", welfareUserOrganization.getUserId())
                    .andEqualTo("firstOrganizationId", organizationUserAddDto.getFirstOrganizationId()))
                    .build();
        }
        int count = welfareUserOrganizationService.selectCountByExample(example);
        if(count>0){
            throw new CommonException("用户在该组织下已存在");
        }
        welfareUserOrganization.setEnterpriseId(organizationUserAddDto.getEnterpriseId());
        welfareUserOrganization.setFirstOrganizationId(organizationUserAddDto.getFirstOrganizationId());
        welfareUserOrganization.setSecondOrganizationId(organizationUserAddDto.getSecondOrganizationId());
        welfareUserOrganization.setThirdOrganizationId(organizationUserAddDto.getThirdOrganizationId());
        welfareUserOrganization.setFourthOrganizationId(organizationUserAddDto.getFourthOrganizationId());
        welfareUserOrganization.setFifthOrganizationId(organizationUserAddDto.getFifthOrganizationId());
        welfareUserOrganization.setStatus(CommonConstants.YES);
        welfareUserOrganization.setCreateTime(new Date());
        welfareUserOrganization.setUpdateTime(new Date());
        return welfareUserOrganizationService.insert(welfareUserOrganization);
    }

    @Override
    public Integer updateUserForEnterpriseOrganization(OrganizationUserUpdDto organizationUserUpdDto) {
        // 查询手机号有没有被使用
        Example userPhoneExample = new Example(WelfareUserWx.class);
        userPhoneExample.createCriteria().andEqualTo("enterpriseId", organizationUserUpdDto.getEnterpriseId())
                .andEqualTo("phone", organizationUserUpdDto.getPhone())
                .andNotEqualTo("status", 0)
                .andNotEqualTo("id", organizationUserUpdDto.getUserId());
        if (welfareUserWxService.selectCountByExample(userPhoneExample) > 0) {
            throw new CommonException("该账户已经存在");
        }
        //查询该用户在新组织下是否存在
        Example example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                .andIsNull("firstOrganizationId")
                .andEqualTo("userId", organizationUserUpdDto.getUserId())
                .andNotEqualTo("id",organizationUserUpdDto.getId())
                .andEqualTo("enterpriseId", organizationUserUpdDto.getEnterpriseId()))
                .build();
        if(EmptyUtils.isNotEmpty(organizationUserUpdDto.getFifthOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andEqualTo("userId", organizationUserUpdDto.getUserId())
                    .andNotEqualTo("id",organizationUserUpdDto.getId())
                    .andEqualTo("fifthOrganizationId", organizationUserUpdDto.getFifthOrganizationId()))
                    .build();
        }else if(EmptyUtils.isNotEmpty(organizationUserUpdDto.getFourthOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("fifthOrganizationId")
                    .andEqualTo("userId", organizationUserUpdDto.getUserId())
                    .andNotEqualTo("id",organizationUserUpdDto.getId())
                    .andEqualTo("fourthOrganizationId", organizationUserUpdDto.getFourthOrganizationId()))
                    .build();
        }else if(EmptyUtils.isNotEmpty(organizationUserUpdDto.getThirdOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("fourthOrganizationId")
                    .andEqualTo("userId", organizationUserUpdDto.getUserId())
                    .andNotEqualTo("id",organizationUserUpdDto.getId())
                    .andEqualTo("thirdOrganizationId", organizationUserUpdDto.getThirdOrganizationId()))
                    .build();
        }else if(EmptyUtils.isNotEmpty(organizationUserUpdDto.getSecondOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("thirdOrganizationId")
                    .andEqualTo("userId", organizationUserUpdDto.getUserId())
                    .andNotEqualTo("id",organizationUserUpdDto.getId())
                    .andEqualTo("secondOrganizationId", organizationUserUpdDto.getSecondOrganizationId()))
                    .build();
        }else if(EmptyUtils.isNotEmpty(organizationUserUpdDto.getFirstOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("secondOrganizationId")
                    .andEqualTo("userId", organizationUserUpdDto.getUserId())
                    .andNotEqualTo("id",organizationUserUpdDto.getId())
                    .andEqualTo("firstOrganizationId", organizationUserUpdDto.getFirstOrganizationId()))
                    .build();
        }
        int count = welfareUserOrganizationService.selectCountByExample(example);
        if(count>0){
            throw new CommonException("用户在该组织下已存在");
        }
        //修改用户信息
        WelfareUserWx welfareUserWx = new WelfareUserWx();
        welfareUserWx.setId(organizationUserUpdDto.getUserId());
        welfareUserWx.setPhone(organizationUserUpdDto.getPhone());
        welfareUserWx.setUserName(organizationUserUpdDto.getName());
        welfareUserWx.setUpdateTime(new Date());
        welfareUserWxService.updateByPrimaryKeySelective(welfareUserWx);
        //查询原用户组织对象信息
        WelfareUserOrganization welfareUserOrganizationOld = welfareUserOrganizationService.selectByPrimaryKey(organizationUserUpdDto.getId());
        Date welfareUserOrganizationOldCreateTime = welfareUserOrganizationOld.getCreateTime();
        //删除用户原组织
        welfareUserOrganizationService.deleteByPrimaryKey(organizationUserUpdDto.getId());
        //创建用户新组织
        WelfareUserOrganization welfareUserOrganization = new WelfareUserOrganization();
        welfareUserOrganization.setEnterpriseId(organizationUserUpdDto.getEnterpriseId());
        welfareUserOrganization.setFirstOrganizationId(organizationUserUpdDto.getFirstOrganizationId());
        welfareUserOrganization.setSecondOrganizationId(organizationUserUpdDto.getSecondOrganizationId());
        welfareUserOrganization.setThirdOrganizationId(organizationUserUpdDto.getThirdOrganizationId());
        welfareUserOrganization.setFourthOrganizationId(organizationUserUpdDto.getFourthOrganizationId());
        welfareUserOrganization.setFifthOrganizationId(organizationUserUpdDto.getFifthOrganizationId());
        welfareUserOrganization.setUserId(organizationUserUpdDto.getUserId());
        welfareUserOrganization.setStatus(CommonConstants.YES);
        welfareUserOrganization.setCreateTime(welfareUserOrganizationOldCreateTime);
        welfareUserOrganization.setUpdateTime(new Date());
       return welfareUserOrganizationService.insertSelective(welfareUserOrganization);
    }


    @Override
    public Integer deleteUserForEnterpriseOrganization(OrganizationUserUpdDto organizationUserUpdDto) {
        WelfareUserOrganization welfareUserOrganizationSelect = new WelfareUserOrganization();
        welfareUserOrganizationSelect.setUserId(organizationUserUpdDto.getUserId());
        if (welfareUserOrganizationService.selectCount(welfareUserOrganizationSelect) < 2) {
            // 删除微信用户表下面的用户记录
            WelfareUserWx welfareUserWxUpd = new WelfareUserWx();
            welfareUserWxUpd.setId(organizationUserUpdDto.getUserId());
            welfareUserWxUpd.setStatus(0);
            welfareUserWxService.updateByPrimaryKeySelective(welfareUserWxUpd);
            // 删除之前的登录token
            Object oldToken = RedisUtil.get("userwx:" + organizationUserUpdDto.getUserId());
            if (EmptyUtils.isNotEmpty(oldToken)) {
                RedisUtil.delete(oldToken.toString());
            }
        }
        // 删除组织下面的该用户
         return welfareUserOrganizationService.deleteByPrimaryKey(organizationUserUpdDto.getId());
    }

    @Override
    public Integer updateUserStopUsed(OrganizationUserUpdDto organizationUserUpdDto) {
        WelfareUserWx welfareUserWxUpd = new WelfareUserWx();
        welfareUserWxUpd.setId(organizationUserUpdDto.getUserId());
        welfareUserWxUpd.setStatus(organizationUserUpdDto.getIsUsed());
        return welfareUserWxService.updateByPrimaryKeySelective(welfareUserWxUpd);
    }

    @Override
    public Integer updateBatchUserOrganization(List<OrganizationUserUpdUserDto> userIdList, UserOrganizationDto userOrganizationDto) {
        //查询该企业下当前组织架构下的所有用户
        Example example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                .andIsNull("firstOrganizationId")
                .andEqualTo("enterpriseId", userOrganizationDto.getEnterpriseId()))
                .build();
        if(EmptyUtils.isNotEmpty(userOrganizationDto.getFifthOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andEqualTo("fifthOrganizationId", userOrganizationDto.getFifthOrganizationId()))
                    .build();
        }else if(EmptyUtils.isNotEmpty(userOrganizationDto.getFourthOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("fifthOrganizationId")
                    .andEqualTo("fourthOrganizationId", userOrganizationDto.getFourthOrganizationId()))
                    .build();
        }else if(EmptyUtils.isNotEmpty(userOrganizationDto.getThirdOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("fourthOrganizationId")
                    .andEqualTo("thirdOrganizationId", userOrganizationDto.getThirdOrganizationId()))
                    .build();
        }else if(EmptyUtils.isNotEmpty(userOrganizationDto.getSecondOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("thirdOrganizationId")
                    .andEqualTo("secondOrganizationId", userOrganizationDto.getSecondOrganizationId()))
                    .build();
        }else if(EmptyUtils.isNotEmpty(userOrganizationDto.getFirstOrganizationId())){
            example= Example.builder(WelfareUserOrganization.class).where(Sqls.custom()
                    .andIsNull("secondOrganizationId")
                    .andEqualTo("firstOrganizationId", userOrganizationDto.getFirstOrganizationId()))
                    .build();
        }
        List<WelfareUserOrganization> list = welfareUserOrganizationService.selectByExample(example);
        //当前组织下的用户id
        Set<Integer> userIdSet = new HashSet<>();
        if(EmptyUtils.isNotEmpty(list)){
            List<Integer> userIdList_ = list.stream().map(WelfareUserOrganization::getUserId).collect(Collectors.toList());
            userIdSet = new HashSet<>(userIdList_);
            //如果移到新组织为原组织，则从userIdSet移除此类用户，重新创建WelfareUserOrganization
            /*for (WelfareUserOrganization welfareUserOrganization : list) {
                if(EmptyUtils.isNotEmpty(userOrganizationDto.getFifthOrganizationId()) && userOrganizationDto.getFifthOrganizationId().equals(welfareUserOrganization.getFifthOrganizationId())){
                    userIdSet.remove(welfareUserOrganization.getUserId());
                }else if(EmptyUtils.isNotEmpty(userOrganizationDto.getFourthOrganizationId()) && userOrganizationDto.getFourthOrganizationId().equals(welfareUserOrganization.getFourthOrganizationId())){
                    userIdSet.remove(welfareUserOrganization.getUserId());
                }else if(EmptyUtils.isNotEmpty(userOrganizationDto.getThirdOrganizationId()) && userOrganizationDto.getThirdOrganizationId().equals(welfareUserOrganization.getThirdOrganizationId())){
                    userIdSet.remove(welfareUserOrganization.getUserId());
                }else if(EmptyUtils.isNotEmpty(userOrganizationDto.getSecondOrganizationId()) && userOrganizationDto.getSecondOrganizationId().equals(welfareUserOrganization.getSecondOrganizationId())){
                    userIdSet.remove(welfareUserOrganization.getUserId());
                }else if(EmptyUtils.isNotEmpty(userOrganizationDto.getFirstOrganizationId()) && userOrganizationDto.getFirstOrganizationId().equals(welfareUserOrganization.getFirstOrganizationId())){
                    userIdSet.remove(welfareUserOrganization.getUserId());
                }else if(EmptyUtils.isEmpty(userOrganizationDto.getEnterpriseId()) && userOrganizationDto.getEnterpriseId().equals(welfareUserOrganization.getEnterpriseId())){
                    userIdSet.remove(welfareUserOrganization.getUserId());
                }
            }*/
        }
        //批量新增用户组织
        List<WelfareUserOrganization> addlist = new ArrayList<>();
        //要删除的用户组织
        List<Integer> userOrgIds = new ArrayList<>();
        for (OrganizationUserUpdUserDto organizationUserUpdUserDto : userIdList) {
            if (!userIdSet.contains(organizationUserUpdUserDto.getUserId())) {
                WelfareUserOrganization welfareUserOrganization = new WelfareUserOrganization();
                welfareUserOrganization.setEnterpriseId(userOrganizationDto.getEnterpriseId());
                welfareUserOrganization.setFirstOrganizationId(userOrganizationDto.getFirstOrganizationId());
                welfareUserOrganization.setSecondOrganizationId(userOrganizationDto.getSecondOrganizationId());
                welfareUserOrganization.setThirdOrganizationId(userOrganizationDto.getThirdOrganizationId());
                welfareUserOrganization.setFourthOrganizationId(userOrganizationDto.getFourthOrganizationId());
                welfareUserOrganization.setFifthOrganizationId(userOrganizationDto.getFifthOrganizationId());
                welfareUserOrganization.setUserId(organizationUserUpdUserDto.getUserId());
                welfareUserOrganization.setStatus(CommonConstants.YES);
                welfareUserOrganization.setCreateTime(new Date());
                welfareUserOrganization.setUpdateTime(new Date());
                addlist.add(welfareUserOrganization);
                userIdSet.add(organizationUserUpdUserDto.getUserId());
            }
            WelfareUserOrganization welfareUserOrganization = welfareUserOrganizationService.selectByPrimaryKey(organizationUserUpdUserDto.getId());
            if(EmptyUtils.isNotEmpty(welfareUserOrganization)){
                if(EmptyUtils.isNotEmpty(userOrganizationDto.getFifthOrganizationId())){
                    if(!userOrganizationDto.getFifthOrganizationId().equals(welfareUserOrganization.getFifthOrganizationId())){
                        userOrgIds.add(organizationUserUpdUserDto.getId());
                    }
                }else if(EmptyUtils.isNotEmpty(userOrganizationDto.getFourthOrganizationId())){
                    if(!userOrganizationDto.getFourthOrganizationId().equals(welfareUserOrganization.getFourthOrganizationId()) || EmptyUtils.isNotEmpty(welfareUserOrganization.getFifthOrganizationId())){
                        userOrgIds.add(organizationUserUpdUserDto.getId());
                    }
                }else if(EmptyUtils.isNotEmpty(userOrganizationDto.getThirdOrganizationId())){
                    if(!userOrganizationDto.getThirdOrganizationId().equals(welfareUserOrganization.getThirdOrganizationId()) || EmptyUtils.isNotEmpty(welfareUserOrganization.getFourthOrganizationId())){
                        userOrgIds.add(organizationUserUpdUserDto.getId());
                    }
                }else if(EmptyUtils.isNotEmpty(userOrganizationDto.getSecondOrganizationId())){
                    if(!userOrganizationDto.getSecondOrganizationId().equals(welfareUserOrganization.getSecondOrganizationId()) || EmptyUtils.isNotEmpty(welfareUserOrganization.getThirdOrganizationId())){
                        userOrgIds.add(organizationUserUpdUserDto.getId());
                    }
                }else if(EmptyUtils.isNotEmpty(userOrganizationDto.getFirstOrganizationId())){
                    if(!userOrganizationDto.getFirstOrganizationId().equals(welfareUserOrganization.getFirstOrganizationId()) || EmptyUtils.isNotEmpty(welfareUserOrganization.getSecondOrganizationId())){
                        userOrgIds.add(organizationUserUpdUserDto.getId());
                    }
                }else if(EmptyUtils.isNotEmpty(welfareUserOrganization.getFirstOrganizationId())){
                    userOrgIds.add(organizationUserUpdUserDto.getId());
                }
            }
        }
        //删除原用户组织
        if(EmptyUtils.isNotEmpty(userOrgIds)){
            welfareUserOrganizationService.deleteByIds(userOrgIds);
        }
        //批量新增用户组织
        if(EmptyUtils.isNotEmpty(addlist)){
            return welfareUserOrganizationService.insertList(addlist);
        }
        return 0;
    }

}
